package com.interfaces;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.common.web.CommonJspKeys;
import com.common.web.CommonKeys;
import com.common.web.Json;
import com.common.web.ReturnCodes;
import com.core.privilege.PrivilegeJspKeys;
import com.core.privilege.bo.PrivilegeBo;
import com.core.privilege.dto.PrivilegeDto;
import com.core.privilege.dto.PrivilegeSearchCondition;
import com.core.privilege.pojo.Privilege;
import com.core.role.dto.RolePo;
import com.core.role.dto.RoleSearchCondition;
import com.core.user.pojo.User;
import com.util.JSONUtil;
import com.util.exception.ComRuntimeException;
import com.util.exception.ComSystemException;
import com.util.framework.BaseController;

@Controller
public class PrivilegeController extends BaseController {
    protected Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private PrivilegeBo privilegeBo;

    public static final String URL_ENTITY = "/privilege";
    public static final String URL_GOTO_MAIN_PAGE = URL_ENTITY + "/goto_main_page";
    public static final String URL_GOTO_ADD_UPDATE_INDEX_PAGE = URL_ENTITY + "/goto_add_update_index_page";
    public static final String URL_GOTO_ADD_UPDATE_PAGE = URL_ENTITY + "/goto_add_update_page";
    public static final String URL_GOTO_ADD_UPDATE_PRIVILEGE_PAGE = URL_ENTITY + "/goto_add_update_privilege_page";
    public static final String URL_GOTO_ADD_PAGE = URL_ENTITY + "/goto_add_page";
    public static final String URL_GOTO_UPDATE_PAGE = URL_ENTITY + "/goto_update_page";
    
    public static final String URL_ADD = URL_ENTITY + "/add";
    public static final String URL_UPDATE = URL_ENTITY + "/update";
    public static final String URL_DELETE_PRIVILEGE_BAT = URL_ENTITY + "/delete_privilege_bat";
    public static final String URL_DELETE = URL_ENTITY + "/delete";
    public static final String URL_MAIN_SEARCH = URL_ENTITY + "/main_search";
    public static final String URL_SEARCH = URL_ENTITY + "/search";
    public static final String URL_SEARCH_NOT = URL_ENTITY + "/search_not";
    public static final String URL_ADD_UPDATE_PRIVILEGE_BAT = URL_ENTITY + "/add_update_privilege_bat";

    @RequestMapping(value = URL_GOTO_MAIN_PAGE, method = RequestMethod.GET)
    public ModelAndView gotoMainPage(PrivilegeSearchCondition usc, HttpSession session) {
        User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);

        ModelAndView modelAndView = new ModelAndView("privilege/privilege_main");
        modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
        //modelAndView.addObject(UserJspKeys.JspParam_UserMainPageModel, model);
        return modelAndView;
    }
    
    @RequestMapping(value = URL_GOTO_ADD_UPDATE_INDEX_PAGE, method = RequestMethod.GET)
    public ModelAndView URL_GOTO_ADD_UPDATE_INDEX_PAGE(Privilege privilege,HttpSession session) {
        User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
        
        ModelAndView modelAndView = new ModelAndView("privilege/privilege_add_update_index");
        modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
        modelAndView.addObject(PrivilegeJspKeys.JspParam_PrivilegeInfo, privilege);
        return modelAndView;
    }
    
    @RequestMapping(value = URL_GOTO_ADD_UPDATE_PAGE, method = RequestMethod.GET)
    public ModelAndView gotoAddUpdatePage(Privilege privilege, HttpSession session) {
        User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
        String url="";
        Privilege privilege1 = privilegeBo.getById(privilege);
        if(privilege1==null){
        	privilege1=privilege;
        	url="privilege/privilege_add";
        }else{
        	url="privilege/privilege_update";
        }
        ModelAndView modelAndView = new ModelAndView(url);
        modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
        modelAndView.addObject(PrivilegeJspKeys.JspParam_PrivilegeInfo, privilege1);
        return modelAndView;
    }
    
    @RequestMapping(value = URL_GOTO_ADD_UPDATE_PRIVILEGE_PAGE, method = RequestMethod.GET)
    public ModelAndView gotoAddUpdatePrivilegePage(Privilege privilege, HttpSession session) {
        User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
        //用户角色查询放到页面，异步请求
        //List<privilege> privilegeList = privilegeBo.searchPojoByUserId(user.getId());
        //user.setprivilegeList(privilegeList);
        ModelAndView modelAndView = new ModelAndView("privilege/privilege_add_update_privilege");
        modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
        modelAndView.addObject(PrivilegeJspKeys.JspParam_PrivilegeInfo, privilege);
        return modelAndView;
    }

    @RequestMapping(value = URL_GOTO_ADD_PAGE, method = RequestMethod.GET)
    public ModelAndView gotoAddPage(HttpSession session) {
        User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);

        ModelAndView modelAndView = new ModelAndView("privilege/privilege_add");
        modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
        return modelAndView;
    }


    @ResponseBody
    @RequestMapping(value = URL_ADD, method = RequestMethod.POST)
    public Json add(Privilege privilege, HttpSession session) {
        Json json = new Json();
        try {
            //User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
            privilegeBo.add(privilege);
            Privilege privilege1=privilegeBo.getByCode(privilege.getCode());
            json.setObj(privilege1.getId());
            json.setSuccess(true);
        } catch (ComRuntimeException e) {
            json = new Json(e.getErrorCode(), e.getMessage());
        } catch (ComSystemException e) {
            log.error("error", e);
            json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
        } catch (Throwable e) {
            log.error("error", e);
            json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... " + e.getMessage());
        }
        return json;
    }

    @RequestMapping(value = URL_GOTO_UPDATE_PAGE, method = RequestMethod.GET)
    public ModelAndView gotoUpdatePage(Privilege privilege, HttpSession session) {
        User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);

        Privilege privilege1 = privilegeBo.getById(privilege);

        ModelAndView modelAndView = new ModelAndView("privilege/privilege_update");
        modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
        modelAndView.addObject(PrivilegeJspKeys.JspParam_PrivilegeInfo, privilege1);
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping(value = URL_UPDATE, method = RequestMethod.POST)
    public Json update(Privilege privilege, HttpSession session) {
        Json json = new Json();
        try {
        	//User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
        	//privilege.setAddprivilegeId(userInfo.getId());
            //privilege.setAddTime(new Date());
            privilegeBo.update(privilege);
            json.setSuccess(true);
        } catch (ComRuntimeException e) {
            json = new Json(e.getErrorCode(), e.getMessage());
        } catch (ComSystemException e) {
            log.error("error", e);
            json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
        } catch (Throwable e) {
            log.error("error", e);
            json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... " + e.getMessage());
        }
        return json;
    }
    
    @ResponseBody
    @RequestMapping(value = URL_MAIN_SEARCH, method = RequestMethod.POST,produces={"application/json;charset=utf-8"})
    public String getPrivilege(PrivilegeSearchCondition usc, HttpSession session) {
        String msg="";
        try {
            List<PrivilegeDto> privilegeList = privilegeBo.searchDto(usc);
            Integer totalRecordCount=privilegeBo.searchCnt(usc);
            if(privilegeList.size()==0){
            	 msg="{\"draw\":"+usc.getDraw()+",\"recordsTotal\":0,\"recordsFiltered\":0,\"data\": []}";
            }else{
            	msg=JSONUtil.toJSONstringNew(privilegeList);
            	//draw:请求次数，recordsTotal：总记录数,recordsFiltered:实际返回数，data:数据（json格式）
            	//datatable分页返回格式，
                msg="{\"draw\":"+usc.getDraw()+",\"recordsTotal\":"+totalRecordCount+",\"recordsFiltered\":"+totalRecordCount+",\"data\": "+msg+"}";
            }
            
        } catch (Exception e) {
            log.error("error", e);
            msg="{\"draw\":"+usc.getDraw()+",\"recordsTotal\":0,\"recordsFiltered\":0,\"data\": []}";
        }
        return msg;
    }
    
    @ResponseBody
    @RequestMapping(value = URL_SEARCH, method = RequestMethod.POST,produces={"application/json;charset=utf-8"})
    public String getPrivilegeByRoleId(RoleSearchCondition usc, HttpSession session) {
        String msg="";
        try {
            //User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
            List<Privilege> privilegeList = privilegeBo.searchPojoByRoleId1(usc);
            Integer totalRecordCount=privilegeBo.searchPojoByRoleIdCnt(usc);
            
           if(privilegeList.size()==0){
           	 msg="{\"draw\":"+usc.getDraw()+",\"recordsTotal\":0,\"recordsFiltered\":0,\"data\": []}";
           }else{
           	msg=JSONUtil.toJSONstringNew(privilegeList);
           	//draw:请求次数，recordsTotal：总记录数,recordsFiltered:实际返回数，data:数据（json格式）
           	//datatable分页返回格式，
               msg="{\"draw\":"+usc.getDraw()+",\"recordsTotal\":"+totalRecordCount+",\"recordsFiltered\":"+totalRecordCount+",\"data\": "+msg+"}";
           }
        } catch (Exception e) {
            log.error("error", e);
            msg="{\"draw\":"+usc.getDraw()+",\"recordsTotal\":0,\"recordsFiltered\":0,\"data\": []}";
        }
        return msg;
    }
    
    @ResponseBody
    @RequestMapping(value = URL_SEARCH_NOT, method = RequestMethod.POST,produces={"application/json;charset=utf-8"})
    public String getAllPrivileges(RoleSearchCondition usc, HttpSession session) {
    	String msg="";
        try {
            //User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
            List<Privilege> privilegeList = privilegeBo.searchPojoByRoleIdNot(usc);
            Integer totalRecordCount=privilegeBo.searchPojoByRoleIdNotCnt(usc);
            
           if(privilegeList.size()==0){
           	 msg="{\"draw\":"+usc.getDraw()+",\"recordsTotal\":0,\"recordsFiltered\":0,\"data\": []}";
           }else{
           	msg=JSONUtil.toJSONstringNew(privilegeList);
           	//draw:请求次数，recordsTotal：总记录数,recordsFiltered:实际返回数，data:数据（json格式）
           	//datatable分页返回格式，
               msg="{\"draw\":"+usc.getDraw()+",\"recordsTotal\":"+totalRecordCount+",\"recordsFiltered\":"+totalRecordCount+",\"data\": "+msg+"}";
           }
        } catch (Exception e) {
            log.error("error", e);
            msg="{\"draw\":"+usc.getDraw()+",\"recordsTotal\":0,\"recordsFiltered\":0,\"data\": []}";
        }
        return msg;
    }
    
    
    
    @ResponseBody
    @RequestMapping(value = URL_ADD_UPDATE_PRIVILEGE_BAT, method = RequestMethod.POST)
    public Json batAdd(RolePo rolePo, HttpSession session) {
        Json json = new Json();
        try {
            //User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
            //List<Role> lst=(List<Role>) JSONUtil.jsonToBeanList(userPo.getUserJson(),List.class,Role.class);
        	String[] strs = rolePo.getRoleJson().split(",");
        	List<Privilege> lst=new ArrayList<Privilege>();
        	Privilege privilege=null;
        	for (int i = 0; i < strs.length; i++) {
        		privilege=new Privilege();
        		privilege.setId(Integer.parseInt(strs[i].trim()));
        		lst.add(privilege);
        	}
            privilegeBo.batAdd(lst,rolePo);
            json.setSuccess(true);
        } catch (ComRuntimeException e) {
            json = new Json(e.getErrorCode(), e.getMessage());
        } catch (ComSystemException e) {
            log.error("error", e);
            json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
        } catch (Throwable e) {
            log.error("error", e);
            json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... " + e.getMessage());
        }
        return json;
    }
    
    @ResponseBody
    @RequestMapping(value = URL_DELETE_PRIVILEGE_BAT, method = RequestMethod.POST)
    public Json batDel(RolePo rolePo, HttpSession session) {
        Json json = new Json();
        try {
            //User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
            //List<Role> lst=(List<Role>) JSONUtil.jsonToBeanList(userPo.getUserJson(),List.class,Role.class);
        	String[] strs = rolePo.getRoleJson().split(",");
        	List<Privilege> lst=new ArrayList<Privilege>();
        	Privilege privilege=null;
        	for (int i = 0; i < strs.length; i++) {
        		privilege=new Privilege();
        		privilege.setId(Integer.parseInt(strs[i].trim()));
        		lst.add(privilege);
        	}
            privilegeBo.batDelete(lst,rolePo);
            json.setSuccess(true);
        } catch (ComRuntimeException e) {
            json = new Json(e.getErrorCode(), e.getMessage());
        } catch (ComSystemException e) {
            log.error("error", e);
            json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
        } catch (Throwable e) {
            log.error("error", e);
            json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... " + e.getMessage());
        }
        return json;
    }
    
    

    @ResponseBody
    @RequestMapping(value = URL_DELETE, method = RequestMethod.POST)
    public Json delete(Privilege privilege) {
        Json json = new Json();
        try {
            privilegeBo.delete(privilege);
            json.setSuccess(true);
        } catch (ComRuntimeException e) {
            json = new Json(e.getErrorCode(), e.getMessage());
        } catch (ComSystemException e) {
            log.error("error", e);
            json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
        } catch (Throwable e) {
            log.error("error", e);
            json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... " + e.getMessage());
        }
        return json;
    }
}
